<template>
  <view class="editor">
    <MyRichTextEditor ref="myEditorRef" />
    <button @click="handleGetEditorContent">获取内容</button>
    <button @click="uploadFileContent">测试文件上传</button>
    <button @click="openUploadFile">文件下载</button>
    <MyUploader />
    <MatchOperator />
  </view>
</template>

<script>
import MyRichTextEditor from "../../components/planTask/MyRichTextEditor.vue";
import MyUploader from "../../components/planTask/MyUploader.vue";
import MatchOperator from "../../components/public/MatchOperator.vue"
export default {
  components: {
    MyRichTextEditor,
    MyUploader,
    MatchOperator
  },
  data() {
    return {};
  },
  methods: {
    uploadFileContent() {
      wx.chooseMessageFile({
        count: 1,
        success(res) {
          // tempFilePath可以作为 img 标签的 src 属性显示图片
          console.log(res.tempFiles);
          wx.cloud.uploadFile({
            cloudPath: `editorFile/${res.tempFiles[0].name}`,
            filePath: res.tempFiles[0].path,
            success: (result) => {
              console.log("文件上传至云存储:", result);
            },
          });
        },
      });
    },
    openUploadFile() {
      wx.cloud.downloadFile({
        fileID:
          "cloud://cloud1-9g2g3ixge22c8a62.636c-cloud1-9g2g3ixge22c8a62-1309337512/editorFile/二叉树引发二级指针的理解.pdf",
        success: (res) => {
          console.log(res.tempFilePath);
          wx.openDocument({
            showMenu: true,
            filePath: res.tempFilePath,
          });
        },
        fail: (err) => {
          console.error(err);
        },
      });
    },
    handleGetEditorContent() {
      return new Promise(async (resolve, reject) => {
        try {
          this.$refs.myEditorRef.getEDitContent().then(async (res) => {
            const tempPic = this.getEditorContentImg(res.html);
            const fileList = [];
            if (tempPic.length) {
              // 组合图片文件，进行上传
              tempPic.forEach((item, index) => {
                const fileName =
                  Math.floor(new Date().getTime() / 1000) + "-" + index;
                fileList.push({ fileName, filePath: item });
              });
              const uploadResult = await this.uploadEditorFile(fileList);
              // 上传至云存储将图片地址替换
              uploadResult.forEach((item, index) => {
                res.html = res.html.replace(tempPic[index], item.fileID);
              });
            }
            console.log("replace:", res.html);
            resolve(res.html);
          });
        } catch (err) {
          console.log("重置文本出错：", err);
          reject(err);
        }
      });
    },

    // 匹配出富文本内容里图片的src数组
    getEditorContentImg(html) {
      const images = html.match(/<img.*?(?:>|\/>)/gi); // 匹配出富文本里的img标签
      if (!images) {
        return [];
      }
      // 匹配出src
      let srcArr = images
        .map((str) => {
          if (!str.match(/ src=[\'\"]?([^\'\"]*)[\'\"]?/i)[1].startsWith("/")) {
            return str.match(/ src=[\'\"]?([^\'\"]*)[\'\"]?/i)[1];
          }
        })
        .filter((src) => !!src);
      return srcArr;
    },
    // 上传富文本当中的图片
    async uploadEditorFile(fileList) {
      try {
        const res = await this.$store.dispatch(
          "m_task/uploadTaskEditorImage",
          fileList
        );
        return res;
      } catch (err) {
        console.log("上传出错：", err);
      }
    },
  },
};
</script>

<style lang="scss">
.editor {
  width: 100%;
  background-color: #fff;
}
</style>
